//进行axios二次封装:使用请求与响应拦截器
import axios from 'axios'
import { message } from 'ant-design-vue';
import { useUserStore } from '@/stores/user'
import utils from "@/utils"

const httpInstance = axios.create({
    baseURL: import.meta.env.VITE_APP_BASE_API,
    timeout: 30000,
    headers: {
        'Content-Type': 'application/json'
    },
})
httpInstance.interceptors.request.use((config) => {
    // console.log(config);
    let userStore=useUserStore();
    let token = userStore.token;
    if (token) {
        config.headers['Authorization'] = token
    }
    return config
}, err => {
    return Promise.reject(err)
});
httpInstance.interceptors.response.use(res => {
    let data =JSON.parse(JSON.stringify(res.data));
    if (data.code===1){
        //失败
        message.error(res.data.msg);
    }
    if (data.code===401){
        //  401 未授权登录 
        message.error(res.data.msg);
        useUserStore().logout();
    }
    if (data.code===403){
        // 403 无权限
        console.log("无权限");
        message.error(res.data.msg);
    }
    
    
    return res.data
}, error => {
    if(error.response.data.code===403){
        message.error("未授权登录");
        let userStore=useUserStore();
        userStore.logout();
    }
    return Promise.reject(error)
})
export default httpInstance